const express = require('express');
const { query } = require('../config/database-sqlite');
const { authenticateToken } = require('../middleware/auth');

const router = express.Router();

// 获取用户收藏列表
router.get('/favorites', authenticateToken, async (req, res) => {
  try {
    const { page = 1, limit = 20 } = req.query;
    const offset = (page - 1) * limit;

    const favorites = await query(`
      SELECT s.*, a.name as artist_name, uf.created_at as favorite_time
      FROM user_favorites uf
      JOIN songs s ON uf.song_id = s.id
      LEFT JOIN artists a ON s.artist_id = a.id
      WHERE uf.user_id = ? AND s.status = 1
      ORDER BY uf.created_at DESC
      LIMIT ? OFFSET ?
    `, [req.user.id, parseInt(limit), parseInt(offset)]);

    res.json({
      favorites,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        hasMore: favorites.length === parseInt(limit)
      }
    });

  } catch (error) {
    console.error('获取收藏列表错误:', error);
    res.status(500).json({ error: '获取收藏列表失败' });
  }
});

// 添加收藏
router.post('/favorites/:songId', authenticateToken, async (req, res) => {
  try {
    const { songId } = req.params;

    // 检查歌曲是否存在
    const songs = await query('SELECT id FROM songs WHERE id = ? AND status = 1', [songId]);
    if (songs.length === 0) {
      return res.status(404).json({ error: '歌曲不存在' });
    }

    // 检查是否已收藏
    const existing = await query(
      'SELECT id FROM user_favorites WHERE user_id = ? AND song_id = ?',
      [req.user.id, songId]
    );

    if (existing.length > 0) {
      return res.status(400).json({ error: '已在收藏列表中' });
    }

    // 添加收藏
    await query(
      'INSERT INTO user_favorites (user_id, song_id) VALUES (?, ?)',
      [req.user.id, songId]
    );

    res.json({ message: '收藏成功' });

  } catch (error) {
    console.error('添加收藏错误:', error);
    res.status(500).json({ error: '添加收藏失败' });
  }
});

// 取消收藏
router.delete('/favorites/:songId', authenticateToken, async (req, res) => {
  try {
    const { songId } = req.params;

    const result = await query(
      'DELETE FROM user_favorites WHERE user_id = ? AND song_id = ?',
      [req.user.id, songId]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ error: '收藏记录不存在' });
    }

    res.json({ message: '取消收藏成功' });

  } catch (error) {
    console.error('取消收藏错误:', error);
    res.status(500).json({ error: '取消收藏失败' });
  }
});

// 获取播放历史
router.get('/history', authenticateToken, async (req, res) => {
  try {
    const { page = 1, limit = 20 } = req.query;
    const offset = (page - 1) * limit;

    const history = await query(`
      SELECT s.*, a.name as artist_name, ph.play_time, ph.play_duration
      FROM play_history ph
      JOIN songs s ON ph.song_id = s.id
      LEFT JOIN artists a ON s.artist_id = a.id
      WHERE ph.user_id = ? AND s.status = 1
      ORDER BY ph.play_time DESC
      LIMIT ? OFFSET ?
    `, [req.user.id, parseInt(limit), parseInt(offset)]);

    res.json({
      history,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        hasMore: history.length === parseInt(limit)
      }
    });

  } catch (error) {
    console.error('获取播放历史错误:', error);
    res.status(500).json({ error: '获取播放历史失败' });
  }
});

// 清空播放历史
router.delete('/history', authenticateToken, async (req, res) => {
  try {
    await query('DELETE FROM play_history WHERE user_id = ?', [req.user.id]);
    res.json({ message: '播放历史清空成功' });

  } catch (error) {
    console.error('清空播放历史错误:', error);
    res.status(500).json({ error: '清空播放历史失败' });
  }
});

// 更新用户信息
router.put('/profile', authenticateToken, async (req, res) => {
  try {
    const { nickname, phone, gender, birthday, signature } = req.body;

    const updateData = {};
    const params = [];

    if (nickname !== undefined) {
      updateData.nickname = '?';
      params.push(nickname);
    }
    if (phone !== undefined) {
      updateData.phone = '?';
      params.push(phone);
    }
    if (gender !== undefined) {
      updateData.gender = '?';
      params.push(gender);
    }
    if (birthday !== undefined) {
      updateData.birthday = '?';
      params.push(birthday);
    }
    if (signature !== undefined) {
      updateData.signature = '?';
      params.push(signature);
    }

    if (Object.keys(updateData).length === 0) {
      return res.status(400).json({ error: '没有要更新的数据' });
    }

    const sql = `UPDATE users SET ${Object.keys(updateData).map(key => `${key} = ?`).join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`;
    params.push(req.user.id);

    await query(sql, params);

    res.json({ message: '用户信息更新成功' });

  } catch (error) {
    console.error('更新用户信息错误:', error);
    res.status(500).json({ error: '更新用户信息失败' });
  }
});

// 获取用户统计信息
router.get('/stats', authenticateToken, async (req, res) => {
  try {
    const [favoriteCount] = await query(
      'SELECT COUNT(*) as count FROM user_favorites WHERE user_id = ?',
      [req.user.id]
    );

    const [historyCount] = await query(
      'SELECT COUNT(*) as count FROM play_history WHERE user_id = ?',
      [req.user.id]
    );

    const [playlistCount] = await query(
      'SELECT COUNT(*) as count FROM playlists WHERE user_id = ? AND status = 1',
      [req.user.id]
    );

    res.json({
      stats: {
        favoriteCount: favoriteCount.count,
        historyCount: historyCount.count,
        playlistCount: playlistCount.count,
        downloadCount: 0 // 暂时设为0
      }
    });

  } catch (error) {
    console.error('获取用户统计错误:', error);
    res.status(500).json({ error: '获取用户统计失败' });
  }
});

module.exports = router;